<?php

DEFINE('MAX_UPLOAD_IMAGE_WIDTH', 4096);
DEFINE('MAX_UPLOAD_IMAGE_HEIGHT', 4096);
DEFINE('MIN_UPLOAD_IMAGE_WIDTH', 0);
DEFINE('MIN_UPLOAD_IMAGE_HEIGHT', 0);
DEFINE('THUMBNAIL_WIDTH', 135);
DEFINE('THUMBNAIL_HEIGHT', 90);

/**
 * Erra_Fields_Image - Handles image field
 *
 * @package
 * @author KPC
 * @copyright Copyright (c) 2012
 * @version $objectId$
 * @access public
 */
class Erra_Fields_Image extends Erra_Fields_Base_Field {

    public $dir;
    public $force_width = null;
    public $force_height = null;
    public $min_width = null;
    public $min_height = null;
    public $max_width = null;
    public $max_height = null;
    public $isUploaded = false;
    public $allowed_ext = null;
    private $_bCropped = false;

    function __construct($objectId) {
        parent::__construct($objectId);
        $this->setDatabaseType('varchar', 256);
    }

    public function editInstance(Array $extraProperties = null) {
        $res = '<div class="erra-form-field-instance">';
        $res .= $this->outputFieldHeader();

        $file = (is_string($this->getRawData())) ? $this->_rawData : '';
        $res .= '<div id="wrapper_file_' . $this->getHtmlId() . '" >
					  <div class="filenamezone">' . $this->getImageDiv() . '</div>';

        if ($this->getRawData() != null) {
            $res .= '<img src="' . $this->getMiniPath() . '" height="100" alt="" /><br/>';
            $res .= '<span class="pointer" id="delete_img_' . $this->getHtmlId() . '" rel="' . $this->getHtmlName() . '"><img src="' . config_get("application.http_webroot") . '/__erra/images' . '/cmsimages/del-btn.png"></span>';
        }
        $res .= '<input type="hidden" name="' . $this->getHtmlName() . '" id="' . $this->getHtmlId() . '" value="' . $this->getRawData() . '" />';
        // $res .= '<input name="MAX_FILE_SIZE" value="10048576" type="hidden" />';
        $res .= '<input name="' . $this->getHtmlId() . '"  id="' . $this->getHtmlId() . '"  type="file" ' . $this->getHtmlAttributes($extraProperties) . ' />';
        $res .= '</div>';
        $res .= '</div>';

        return $res;
    }

    public function getMiniPath() {
        $fileName = explode('/', $this->getRawData());
        if (is_array($fileName) && count($fileName) > 0) {
            $fileName[count($fileName) - 1] = 'mini-' . $fileName[count($fileName) - 1];
            $fileName = implode('/', $fileName);
        } else {
            $fileName = $this->getRawData();
        }
        return config_get("path.public_upload_directory") . '/' . $fileName;
    }

    function getPath() {
        return config_get('path.public_upload_directory') . '/' . $this->getRawData();
    }

    function toHtml($displayParameters = null) {
        $rawData = $this->getRawData();
        if (is_string($rawData) && $rawData) {
            return '<div class="' . get_class($this) . '"><img src="' . config_get('path.public_upload_directory') . '/' . $this->getRawData() . '" /></div>';
        }
        return __('No image');
    }

    function getImageDiv() {
        $file = (is_string($this->getRawData())) ? $this->_rawData : '';

        $ext = (is_string($this->getRawData()) && strlen($this->_rawData) > 4) ? get_file_ext($this->_rawData) : 'x';
        // $file = '<input type="text" class="filename_select" size="15" value="'.config_get("application.http_webroot").'/__files/'.$file.'" />';
        if ($ext) {
            switch (strtolower($ext)) {
                case 'doc': $pos = '0';
                    break;

                case 'bmp': $pos = '16';
                    break;

                case 'jpg': $pos = '32';
                    break;

                case 'jpeg': $pos = '32';
                    break;

                case 'png': $pos = '48';
                    break;

                case 'gif': $pos = '64';
                    break;

                case 'psd': $pos = '80';
                    break;

                case 'mp3': $pos = '96';
                    break;

                case 'wav': $pos = '96';
                    break;

                case 'ogg': $pos = '96';
                    break;

                case 'avi': $pos = '112';
                    break;

                case 'wmv': $pos = '112';
                    break;

                case 'flv': $pos = '112';
                    break;

                case 'pdf': $pos = '128';
                    break;

                case 'exe': $pos = '144';

                    break;

                case 'txt': $pos = '160';
                    break;

                default: $pos = '176';
                    break;
            };

            return '<div style="display:block; background:url(' . config_get("application.http_webroot") . '/__erra/images' . '/filestyle/icons.png) no-repeat 0 -' . $pos . 'px; padding-left:20px;">' . $file . '</div>';
        }
    }

    public function saveUploaded($destination, $ext = null, $errMessage = null) {
        // Set defaults
        $minWidth = is_null($this->min_width) ? MIN_UPLOAD_IMAGE_WIDTH : $this->min_width;
        $minHeight = is_null($this->min_height) ? MIN_UPLOAD_IMAGE_HEIGHT : $this->min_height;
        $maxWidth = is_null($this->max_width) ? MAX_UPLOAD_IMAGE_WIDTH : $this->max_width;
        $maxHeight = is_null($this->max_height) ? MAX_UPLOAD_IMAGE_HEIGHT : $this->max_height;

        if (isset($_FILES[$this->getHtmlId()]) && !empty($_FILES[$this->getHtmlId()]['name'])) {
            $errMessage = (!is_null($errMessage)) ? str_replace('_FILENAME_', $_FILES[$this->getHtmlId()]['name'], $errMessage) : $errMessage;

            if ($_FILES[$this->getHtmlId()]['error']) {
                switch ($_FILES[$this->getHtmlId()]['error']) {
                    case 1: // UPLOAD_ERR_INI_SIZE
                        $this->setMessage(__("Le fichier dépasse la limite autorisée par le serveur (fichier php.ini) !"));
                        return false;

                    case 2: // UPLOAD_ERR_FORM_SIZE
                        $this->setMessage(__("Le fichier dépasse la limite autorisée dans le formulaire HTML !"));
                        return false;

                    case 3: // UPLOAD_ERR_PARTIAL
                        $this->setMessage(__("L'envoi du fichier a été interrompu pendant le transfert !"));
                        return false;

                    case 4: // UPLOAD_ERR_NO_FILE
                        $this->setMessage(__("Le fichier que vous avez envoyé a une taille nulle !"));
                        return false;
                }
            } else {
                $filename = strip_accents($_FILES[$this->getHtmlId()]['name']);
                $fileExtension = get_file_ext($filename);
                $filename = str_lreplace('.' . $fileExtension, '', $filename);
                $filename .= '-' . uniqid() . '.' . $fileExtension;

                $mini_destination = str_replace('_FILENAME_', 'mini-' . $filename, $destination);
                $destination = str_replace('_FILENAME_', $filename, $destination);


                $ext = (!is_null($ext)) ? explode('|', $ext) : null;
                $extIsValid = (!is_null($ext)) ? false : true;
                foreach ($ext as $extension) {
                    $extension = str_replace('.', '', $extension);
                    if (strtolower($extension) == strtolower($fileExtension))
                        $extIsValid = true;
                }

                if (!$extIsValid) {
                    $this->setMessage((!is_null($errMessage)) ? $errMessage : __("Le fichier a une extension invalide"));
                    return false;
                }

                $path = dirname($destination);

                if (!is_dir('__files/' . $path)) {
                    mkdir('__files/' . $path, 0777, true);
                }

                move_uploaded_file($_FILES[$this->getHtmlId()]['tmp_name'], '__files/' . $destination);

                $ext = get_file_ext($destination);

                if (strcasecmp($ext, 'jpg') == 0 || strcasecmp($ext, 'png') == 0 || strcasecmp($ext, 'gif') == 0) {
                    $image = new Erra_Utils_Image('__files/' . $destination);

                    $toResize = false;
                    $optWidth = $optHeight = null;
                    // If image is too large, set optimal proportions
                    if ($image->getWidth() > $maxWidth) {
                        $optWidth = $maxWidth;
                    }
                    if ($image->getHeight() > $maxHeight) {
                        $optHeight = $maxHeight;
                    }
                    // Compute optimal size
                    if (is_numeric($optWidth) && is_numeric($optHeight)) {
                        $toResize = true;
                    } else if (is_numeric($optWidth) && $image->getWidth() > $optWidth) {
                        $w = $image->getWidth();
                        $h = $image->getHeight();
                        $optHeight = (int) (($optWidth / $w) * $h);
                        $toResize = true;
                    } else if (is_numeric($optHeight) && $image->getHeight() > $optHeight) {
                        $w = $image->getWidth();
                        $h = $image->getHeight();
                        $optWidth = (int) (($optHeight / $h) * $w);
                        $toResize = true;
                    } else if (is_numeric($minWidth) && $image->getWidth() < $minWidth) {
                        $w = $image->getWidth();
                        $h = $image->getHeight();
                        $optWidth = $minWidth;
                        $optHeight = (int) (($minWidth / $w) * $h);
                        $toResize = true;
                    } else if (is_numeric($minHeight) && $image->getHeight() < $minHeight) {
                        $w = $image->getWidth();
                        $h = $image->getHeight();
                        $optHeight = $minHeight;
                        $optWidth = (int) (($minHeight / $h) * $w);
                        $toResize = true;
                    }
                    // Force width and/or height
                    if (is_numeric($this->force_width) && $this->force_width > 0) {
                        $toResize = true;
                        $w = $image->getWidth();
                        $h = $image->getHeight();
                        $optWidth = $this->force_width;
                        $optHeight = (is_numeric($this->force_height)) ? $this->force_height : (int) (($h / $w) * $optWidth);
                    }
                    if (is_numeric($this->force_height) && $this->force_height > 0) {
                        $toResize = true;
                        $w = $image->getWidth();
                        $h = $image->getHeight();
                        $optHeight = $this->force_height;
                        $optWidth = (is_numeric($this->force_width)) ? $this->force_width : (int) (($w / $h) * $optHeight);
                    }

                    if ($toResize) {
                        // Create thumbnail
                        if ($this->getCropped() == true) {
                            $image->resizeCropped($optWidth, $optHeight);
                        } else {
                            $image->resize($optWidth, $optHeight);
                        }
                        $image->save('__files/' . str_replace('.png', '.jpg', $destination));
                    }
                    // Create thumbnail
                    if ($this->getCropped() == true) {
                        $image->resizeCropped(135, 90);
                    } else {
                        $image->resize(135, 90);
                    }
                    $image->save('__files/' . str_replace('.png', '.jpg', $mini_destination));
                }

                $this->setRawData(str_replace('.png', '.jpg', $destination));

                $this->setMessage(null);
                $this->isUploaded = true;

                return true;
            }
        } else if (!isset($_FILES[$this->getHtmlId()]) && $this->isRequired == true) {
            $this->setMessage(__('Please choose a file'));

            return false;
        }

        $this->setMessage(null);

        return null;
    }

    /** Getters and setters */
    public function getCropped() {
        return $this->_bCropped;
    }

    public function setCropped($bCropped) {
        $this->_bCropped = $bCropped;
        return $this;
    }

    public function setWidth($width) {
        $this->force_width = $width;
        return $this;
    }

    public function setHeight($width) {
        $this->force_height = $width;
        return $this;
    }

    public function setMinWidth($width) {
        $this->min_width = $width;
        return $this;
    }

    public function setMinHeight($width) {
        $this->min_height = $width;
        return $this;
    }

    public function setMaxWidth($width) {
        $this->max_width = $width;
        return $this;
    }

    public function setMaxHeight($width) {
        $this->max_height = $width;
        return $this;
    }

    public function setDir($dir) {
        $this->dir = $dir;
        return $this;
    }

    public function setAllowedExt($allowed) {
        $this->allowed_ext = $allowed;
        return $this;
    }

}

?>